package com.platform.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.platform.dao.ApiCartMapper;
import com.platform.entity.CartVo;
import com.platform.entity.TbGoodsFixingsVo;
import com.platform.entity.TbGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ApiCartService {
    @Autowired
    private ApiCartMapper cartDao;

    @Autowired
    private ApiTbGoodsService apiTbGoodsService;

    public CartVo queryObject(Integer id) {
        return cartDao.queryObject(id);
    }


    public List<CartVo> queryList(Map<String, Object> map) {
        return cartDao.queryList(map);
    }


    public int queryTotal(Map<String, Object> map) {
        return cartDao.queryTotal(map);
    }


    /**
     * 保存购物车，
     * 1、判断购物车中是否存在相同的商品，如果存在数量增加。
     * 2、判断库存数量是否够用
     * @param cart
     * @return
     */
    public String save(CartVo cart) {
        //商品数量
        int num=cart.getNumber();
        Map cartParam = new HashMap();
        cartParam.put("goods_id", cart.getGoods_id());
        cartParam.put("user_id", cart.getUser_id());
        cartParam.put("goods_specifition_ids", cart.getGoods_specifition_ids());
        List<CartVo> cartInfoList = cartDao.queryList(cartParam);
        CartVo cartInfo = null != cartInfoList && cartInfoList.size() > 0 ? cartInfoList.get(0) : null;

        //如果存在相同规格的商品，则增加数量
        if (null != cartInfo) {
            num=cartInfo.getNumber()+cart.getNumber();
            cart.setNumber(num);
        }

        String result=chackNumber(cart);
        if(result==null){
            //如果存在相同规格的商品,更新，否则新增
            if (null != cartInfo) {
                cart.setId(cartInfo.getId());
                cartDao.update(cart);
            }else{
                cartDao.save(cart);
            }
        }
        return result;
    }

    public String chackNumber(CartVo cart){
        int num = cart.getNumber();
        TbGoodsVo goodsInfo = apiTbGoodsService.getTbGoodsVoById(cart.getGoods_id());
        if(num > goodsInfo.getGood_num()){
            return "商品["+goodsInfo.getName()+"]库存不足";
        }else{
            JSONArray goodSpes = JSON.parseArray(cart.getFixings());
            for(int i =0;i<goodSpes.size();i++){
                JSONObject jGood=goodSpes.getJSONObject(i);
                //商品id相同，不做二次判断
                if(jGood.getInteger("id")!=goodsInfo.getId()){
                    //套餐内商品信息
                    TbGoodsVo jGoodsInfo = apiTbGoodsService.getTbGoodsVoById(jGood.getInteger("id"));
                    if(jGood.getInteger("number")*num > jGoodsInfo.getGood_num()){
                        return "商品["+jGoodsInfo.getName()+"]库存不足";
                    }
                }
                //从数据库获取商品下所有规格信息
                Map<Integer, TbGoodsFixingsVo> fixMap=apiTbGoodsService.queryGoodsFix(jGood.getInteger("id"));
                //判断选中规格的库存是否够用，选中规格的数量为   商品数量*规格数量
                for(int ii=0;ii<jGood.getJSONArray("fixType").size();ii++){
                    JSONArray fixs=jGood.getJSONArray("fixType").getJSONObject(ii).getJSONArray("fixs");
                    for(int j=0;j<fixs.size();j++){
                        JSONObject fixJson=fixs.getJSONObject(j);
                        //选择的规格需要判断库存信息
                        if(fixJson.getInteger("checked")==1){
                            //库存不限的不予判断
                            if(fixMap.get(fixJson.getInteger("id")).getGood_num()!=-1){
                                //数据库中存在该规格
                                if(fixMap.get(fixJson.getInteger("id"))!=null){
                                    if(fixJson.getInteger("number")*num > fixMap.get(fixJson.getInteger("id")).getGood_num()){
                                        return "商品["+fixJson.getString("name")+"]库存不足";
                                    }
                                }else{
                                    return "商品["+fixJson.getString("name")+"]商品错误";
                                }
                            }
                        }
                    }
                }

            }
        }
        return null;
    }

    public void update(CartVo cart) {
        cartDao.update(cart);
    }


    public void delete(Integer id) {
        cartDao.delete(id);
    }


    public void deleteByIds(Integer[] ids){
        cartDao.deleteBatch(ids);
    }


    public void deleteBatch(Integer[] ids) {
        cartDao.deleteBatch(ids);
    }

    public void updateCheck(Integer id,Integer isChecked){
        CartVo cart = new CartVo();
        cart.setId(id);
        cart.setChecked(isChecked);
        cartDao.update(cart);
    }

    public void updateCheck(String[] productIds, Integer isChecked, Long userId) {
        cartDao.updateCheck(productIds, isChecked, userId);

        // 判断购物车中是否存在此规格商品
        Map cartParam = new HashMap();
        cartParam.put("user_id", userId);
        List<CartVo> cartInfoList = cartDao.queryList(cartParam);
        Map crashParam = new HashMap();
        List<Integer> goods_ids = new ArrayList();
        List<CartVo> cartUpdateList = new ArrayList();
        for (CartVo cartItem : cartInfoList) {
            if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {
                goods_ids.add(cartItem.getGoods_id());
            }
            if (!cartItem.getRetail_price().equals(cartItem.getRetail_product_price())) {
                cartItem.setRetail_price(cartItem.getRetail_product_price());
                cartUpdateList.add(cartItem);
            }
        }
        if (null != goods_ids && goods_ids.size() > 0) {
            crashParam.put("goods_ids", goods_ids);
            for (CartVo cartItem : cartInfoList) {
                // 存在原始的
                if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {
                    for (CartVo cartCrash : cartInfoList) {
                        if (null != cartItem.getChecked() && 1 == cartItem.getChecked() && !cartCrash.getId().equals(cartItem.getId())) {
                            cartUpdateList.add(cartCrash);
                            break;
                        }
                    }
                }
            }
        }
        if (null != cartUpdateList && cartUpdateList.size() > 0) {
            for (CartVo cartItem : cartUpdateList) {
                cartDao.update(cartItem);
            }
        }
    }

    public void deleteByProductIds(String[] productIds) {
        cartDao.deleteByProductIds(productIds);
    }

    public void deleteByUserAndProductIds(Long userId, String[] productIds) {
        cartDao.deleteByUserAndProductIds(userId, productIds);
    }

    public void deleteByCart(Long user_id, Integer session_id, Integer checked) {
        cartDao.deleteByCart(user_id, session_id, checked);
    }

}
